// socket已经连接成功
let socketOpen = false
// socket已经调用关闭function
let socketClose = false
// 判断心跳变量
let heart = ''
// 心跳失败次数
let heartBeatFailCount = 0;
// 终止心跳
let heartBeatTimeOut = null;
// 终止重新连接
let connectSocketTimeOut = null;


/**
 * 创建连接并开启
 * @param {*} wss URL 
 */
function connect(callback){
    socketOpen = false;
    socketClose = false;

    let loginToken = '';
    if(app.globalData.userInfo){
        loginToken = app.globalData.userInfo.loginToken
    }
    //创建连接
    wx.connectSocket({
      url: 'xxx',
      header:{
        'content-type': 'application/json',
        'authorization': loginToken,
      },
      success(res){
        if(callback){
            callback.call({code:200});
        }
      },
      fail(res){
        if(callback){
            callback.call({code:201});
        }
      }
    })
}

/**
 * 发送数据
 * @param {*} data 发送内容
 */
function sendSocket(data,callback){
    if(socketOpen){
        wx.sendSocketMessage({
          data: data,
          success(res){
            if(callback){
                callback.call({code:200});
            }
          },
          fail(res){
            if(callback){
                callback.call({code:202});
            }
          }
        })
    }
}

/**
 * 关闭socket
 */
function closeSocket(callback){
    if(connectSocketTimeOut){
        clearTimeout(connectSocketTimeOut);
        connectSocketTimeOut = null;
    }
    socketClose = true;
    const self = this;
    self.stopHeartBeat();

    wx.closeSocket({
        code:1000, //一个数字值表示关闭连接的状态号，表示连接被关闭的原因
        success(res){
            console.log("WebSocket已关闭！");
            if(callback){
                callback.call({code:200});
            }
        },
        fail(res){
            if(callback){
                callback.call({code:203});
            }
        }
    })
}

// 开始心跳
function startHeartBeat(){
    console.log('socket开始心跳')
    heart = 'heart';
    this.heartBeat();
}

// 心跳
function heartBeat(){
    const self = this;
    if (!heart) return;
    self.sendSocket(JSON.stringify({'msg_type': 'heart'}),res=>{
        if(res.code==200){
            console.log('socket心跳...bobobo...');
        }else{
            console.log('socket心跳失败...滴____');
            if (heartBeatFailCount > 2) {
                // 重连
                self.connect();
            }
            heartBeatFailCount++;
        }
        if (heart) {
            heartBeatTimeOut = setTimeout(() => {
                self.heartBeat();
            }, 5000);
        }
    })

}

// 结束心跳
function stopHeartBeat(){
    console.log('socket结束心跳')
    heart = '';
    if (heartBeatTimeOut) {
      clearTimeout(heartBeatTimeOut);
      heartBeatTimeOut = null;
    }
    if (connectSocketTimeOut) {
      clearTimeout(connectSocketTimeOut);
      connectSocketTimeOut = null;
    }
}

/**监听 */
function monitor(receiving){
    const self = this;
    // 监听WebSocket连接打开事件。callback 回调函数
    wx.onSocketOpen(function(res) {
        console.log('监听：WebSocket连接已打开！')
        // 如果已经调用过关闭function
        if (socketClose) {
            self.closeSocket();
        }else{
            socketOpen = true;
            self.startHeartBeat();
        }
    })
   
    // 监听WebSocket错误。
    wx.onSocketError(function(res) {
        console.log('监听：WebSocket连接打开失败，请检查！', res);
        if(receiving){
            receiving(res);
        }
    })
    
    // 监听WebSocket接受到服务器的消息事件。
    wx.onSocketMessage(function(res) {
        console.log('监听：收到服务器内容：' + res.data)
    })
    
    // 监听WebSocket关闭。
    wx.onSocketClose(function(res) {
        console.log('监听：WebSocket 已关闭！')
        if (!socketClose) {
            clearTimeout(connectSocketTimeOut)
            connectSocketTimeOut = setTimeout(() => {
                self.connect();
            }, 3000);
        }
    })
}

module.exports = {
    connect:connect,
    closeSocket:closeSocket,
    monitor:monitor
}